'use strict';

angular.module('snPaas_om').service('clusterStore',['SpHttp','$q','baseUrl',function($http,$q,baseUrl){
	var query = function(){
		var deferred = $q.defer();
		$http.get('/rest/cluster/list').success(function(data,status){
			deferred.resolve(data.data);
		});
		return deferred.promise;
	};
	var save = function(params){
		var deferred = $q.defer();
		params.components = JSON.stringify(params.components);
		$http({
			    method: 'POST',
			    url: baseUrl.ajax+'/rest/cluster/save',
			    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
			    data: $.param(params),
			}).success(function (resp) {
				deferred.resolve(resp.data.deployId);
			}).error(function(resp){
				deferred.reject(resp);
			});
		return deferred.promise;
	};
	var deploy = function(p){
		var deferred = $q.defer();
		var deployFn = function(params,d){
			$http({
			    method: 'POST',
			    url: baseUrl.ajax+'/rest/cluster/create',
			    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
			    data: $.param({deployId:params}),
			}).success(function (resp) {
				d.resolve(resp.data);
			}).error(function(resp){
				d.reject(resp);
			});
		};
		if(typeof p == 'string'){
			deployFn(p,deferred);
		}
		else{
			save(p).then(function(data){
				deployFn(data,deferred);
			},function(data){
				deferred.reject(data);
			});
		}
		return deferred.promise;
	};
	var detail = function(deployId){
		var deferred = $q.defer();
		$http.get('/rest/cluster/detail',{params:{deployId:deployId}}).success(function(data,status){
			deferred.resolve(data.data);
		});
		return deferred.promise;
	};
	var remove = function(deployId){
		var deferred = $q.defer();
		$http.get('/rest/cluster/delete',{params:{deployId:deployId}}).success(function(data,status){
			deferred.resolve(data.data);
		});
		return deferred.promise;
	};
	var getDirectorUuid = function(){
		var deferred = $q.defer();
		$http.get('/rest/cluster/getDirectorUuid').success(function(data,status){
			deferred.resolve(data.data.directorUuid);
		});
		return deferred.promise;
	};
	var checkName = function(name){
		var deferred = $q.defer();
		$http.get('/rest/cluster/checkName',{params:{clusterName:name}}).success(function(data,status){
			deferred.resolve(data.data);
		});
		return deferred.promise;
	};
	return {
		query:query,
		save:save,
		deploy:deploy,
		detail:detail,
		remove:remove,
		getDirectorUuid:getDirectorUuid,
		checkName:checkName

	};
}]);